var log, className = "dark", newCount = 0;
var setting = {
	view: {
		addHoverDom: addHoverDom,
		removeHoverDom: removeHoverDom,
		selectedMulti: false
	},
	edit: {
		enable: true,
		// 显示编辑图标
		editNameSelectAll: false,
		// 取消节点文本被选中
		showRemoveBtn: showRemoveBtn,
		showRenameBtn: showRenameBtn,
		renameTitle: "编辑",
		removeTitle: "删除"
	},
	data: {
		simpleData: {
			enable: true,
			idKey: "id",
			pIdKey: "pid",
			rootPId: 0
		}
	},
	callback: {
		beforeDrag: beforeDrag,
		beforeEditName: beforeEditName,
		beforeRemove: beforeRemove,
		beforeRename: beforeRename,
		onRemove: onRemove,
		onRename: onRename,
		onClick: onClick
	}
};

// 获取菜单
function getMenu(pubno) {
	$.ajax({
	      url: path + '/menu/wxmenu',
	      type: 'GET',
	      data: { pubno: pubno },
	      dataType: 'JSON',
	      success: function(data) {
	       	if (data.success) {
	       		initMenu(data.list);
			} else {
				alert(data.message);
			}
	      },
	      error: function(e) {
		      if (e.responseText == 'unlogin') {
		          location.href = '${path}/login';
		      }
		  }
	  });
}

// 初始加载树节点
function initMenu(zNodes) {
	newCount = zNodes.length;
	for (var i = 0; i < zNodes.length; i ++) {
		zNodes[i]['keyId'] = zNodes[i].id;
		zNodes[i]['id'] = zNodes[i].menuId;
		zNodes[i]['pid'] = zNodes[i].parentMenuId;
		zNodes[i]['name'] = zNodes[i].name;
		if (zNodes[i].parentMenuId == 0) {
			zNodes[i]['open'] = true;
		}
	}
	//console.log('zNodes', zNodes);
	$.fn.zTree.init($("#treeDemo"), setting, zNodes);
	$("#selectAll").bind("click", selectAll);
}

// 删除节点
function onRemove(e, treeId, treeNode) {
	$.post(path + '/menu/deleteMenu', { id: treeNode.keyId }, function(res) {
		console.log('删除', res)
	});
	$('#rndiv').hide();
	showLog("[ " + getTime() + " onRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
}

// 创建菜单
function createMenu() {
	// 创建菜单前组装菜单数据
	var jsondata = getMenuJson();
	if (jsondata != null && jsondata.length > 0) {
		$.post(path + '/menu/createMenu', { jsondata: jsondata, pubno: $("#pubno").val() },
		function(data) {
			var errcode = data.result;
			var res = errcode == 0 ? '菜单创建成功' : ('菜单创建失败：errcode = ' + errcode);
			alert(res);
		});
	}
}

// 选择图文
function selectImageText() {
	var url = path + '/imagetextmore/selectList';
	var attr = 'width=1000px,height=500px,status=no,scroll=yes,top=150px,left=200px';
	//弹窗改为window.open()解决谷歌浏览器不支持弹窗的特性
	window.open(url, window, attr);
}

// 节点显示图标
function addHoverDom(treeId, treeNode) {
	//alert("pid = " + treeNode.pid + ", tId = "+treeNode.tId+", treeId = " + treeId);
	if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;

	if (treeNode.pid == 0) {
		var sObj = $("#" + treeNode.tId + "_span");
		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='添加' onfocus='this.blur();'></span>";
		sObj.after(addStr);
	}

	var btn = $("#addBtn_" + treeNode.tId);
	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
	if (btn) btn.bind("click",
	function() {
		newCount ++;
		var nodeId = 100 + newCount;
		var sNodes = zTree.getNodesByParam("pid", treeNode.id, null);
		// 添加一级节点
		if (treeNode.pid == 0 && treeNode.id == 0) {
			if (sNodes.length <= 3) {
				zTree.addNodes(treeNode, {
					id: nodeId,
					pid: treeNode.id,
					name: 'node' + newCount,
					refText: '',
					type: 'click_text'
				});
				//----------------显示编辑区----------------begin
				var nd = zTree.getNodeByParam('id', nodeId, null);
				showInfo(nd);
				//----------------显示编辑区----------------end
			} else {
				alert("最多只能添加3个一级菜单!");
			}
		}
		// 添加二级节点
		if (treeNode.pid == 0 && treeNode.id != 0) {
			if (sNodes.length < 5) {
				zTree.addNodes(treeNode, {
					id: nodeId,
					pid: treeNode.id,
					name: 'node' + newCount,
					refText: '',
					type: 'click_text'
				});
				//----------------显示编辑区----------------begin
				var nd = zTree.getNodeByParam('id', nodeId, null);
				showInfo(nd);
				//----------------显示编辑区----------------end
			} else {
				alert("最多只能添加5个二级菜单!");
			}
		}
	});
}

function beforeDrag(treeId, treeNodes) {
	return false;
}

// 删除节点事件
function beforeRemove(treeId, treeNode) {
	//删除一级节点只在其没有二级节点时
	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
	if (treeNode.pid == 0) {
		var sNodes = zTree.getNodesByParam("pid", treeNode.id, null);
		if (sNodes.length > 0) {
			alert("请先删除二级节点！");
			return false;
		}
	}
	className = (className === "dark" ? "": "dark");
	showLog("[ " + getTime() + " beforeRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);

	zTree.selectNode(treeNode);
	return confirm("确认删除 节点 -- " + treeNode.name + " 吗？");
}

// 点击编辑图标弹出编辑区
function beforeEditName(treeId, treeNode) {
	showInfo(treeNode);
}

function beforeRename(treeId, treeNode, newName, isCancel) {
	className = (className === "dark" ? "": "dark");
	//菜单上编辑名称，同步右边菜单名称显示
	$('input[name=name]').val(newName);

	showLog((isCancel ? "<span style='color:red'>": "") + "[ " + getTime() + " beforeRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>": ""));
	if (newName.length == 0) {
		alert("菜单名称不能为空!");
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		setTimeout(function() {
			zTree.editName(treeNode);
		}, 10);
		return false;
	}
	return true;
}

// 暂不使用
function onRename(e, treeId, treeNode, isCancel) {
	//菜单上编辑名称，同步右边菜单名称显示
	//$('input[name=name]').val(treeNode.name);
	//showLog((isCancel ? "<span style='color:red'>":"") + "[ "+getTime()+" onRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>":""));
}

// 显示删除图标
function showRemoveBtn(treeId, treeNode) {
	if (treeNode.id == 0) {
		return !treeNode.isFirstNode; //第一个节点不显示删除图标
	}
	if (treeNode.id > 0) {
		return treeNode;
	}
}

// 显示编辑图标
function showRenameBtn(treeId, treeNode) {
	if (treeNode.id == 0) {
		return !treeNode.isFirstNode;
	}
	if (treeNode.id > 0) {
		return treeNode;
	}
}

function showLog(str) {
	if (!log) log = $("#log");
	log.append("<li class='" + className + "'>" + str + "</li>");
	if (log.children("li").length > 8) {
		log.get(0).removeChild(log.children("li")[0]);
	}
}

function getTime() {
	var now = new Date(),
	h = now.getHours(),
	m = now.getMinutes(),
	s = now.getSeconds(),
	ms = now.getMilliseconds();
	return (h + ":" + m + ":" + s + " " + ms);
}

function removeHoverDom(treeId, treeNode) {
	$("#addBtn_" + treeNode.tId).unbind().remove();
}

function selectAll() {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
	zTree.setting.edit.editNameSelectAll = $("#selectAll").attr("checked");
}

// 点击节点
function onClick() {
	var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	var sltNode = treeObj.getSelectedNodes();
	if (sltNode != null && sltNode.length > 0) {
		var treeNode = sltNode[0];
		// 显示编辑区 
		if (treeNode != null && treeNode.id != 0) {
			showInfo(treeNode);
		}
	}
}

// 显示编辑区
function showInfo(treeNode) {
	$('#rndiv').show();
	//一级包含二级，则此一级菜单不显示编辑区
	/*var zTree = $.fn.zTree.getZTreeObj("treeDemo");
	if (treeNode.pid == 0) {
		var sNodes = zTree.getNodesByParam("pid", treeNode.id, null);
		if (sNodes.length > 0) {
			return false;
		}
	}*/
	
	// 编辑区赋值
	$('input[name=id]').val(treeNode.keyId);
	$('input[name=menuId]').val(treeNode.id);
	$('input[name=name]').val(treeNode.name);
	$('input[name=mkey]').val(treeNode.mkey);
	$('input[name=parentMenuId]').val(treeNode.pid);
	$('input[name=name]').focus();
	$('#trid').val(treeNode.tId); //保存tId到隐藏域
	
	// 设置可视化
	setDisplay(treeNode);
}

// 菜单选择改变事件
function changeMenuType(obj) {
	var tid = $('#trid').val();
	var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	var treeNode = treeObj.getNodeByTId(tid);
	// 设置可视化
	treeNode.type = obj.value;
	setDisplay(treeNode);
}

/**
 * 设置可视化
 * @param treeNode
 * @returns
 */
function setDisplay(treeNode) {
	// 下拉框保值
	$("#type").val(treeNode.type);
	// 设置可视化
	var arr = ['view', 'click_text', 'click_imgtxt', 'miniprogram'];
	for (var i = 0; i < arr.length; i ++) {
		if(treeNode.type == arr[i]) {
			$('#' + arr[i]).show();
		} else {
			$('#' + arr[i]).hide();
		}
	}
	if (treeNode.type == 'click_text') { //文本
		$('#content').val(treeNode.refText);
	} else if (treeNode.type == 'click_imgtxt') { //图文
		/*var treedata = $('#treedata').val();
		if (treedata.indexOf(treeNode.id) > -1 && treeNode.type == 2) {
			showImgTxtHtml(treeNode.id); //查询图片html
		} else {
			$('#url').val("");
			$('#preViewDiv').html('');
			$('#content').val("");
		}
		$('#preViewDiv').show();
		$('#preViewDiv').addClass("divimg");*/
	} else if (treeNode.type == 'view') { //链接
		$('input[name=url]').val(treeNode.url);
	} else if (treeNode.type == 'miniprogram') { //小程序
		$('input[name=appid]').val(treeNode.appid);
		$('input[name=pagepath]').val(treeNode.pagepath);
	}
}

// 校验节点填写
function checkForm() {
	var tid = $('#tid').val();
	var type = $('#type').val();
	var content = $('#content').val();
	var url = $('input[name=url]').val();
	var name = $('input[name=name]').val();
	$('#imghtml').val($('#preViewDiv').html());
	if (name == "") {
		alert('菜单名称不能为空!');
		return false;
	}
	if (name.indexOf("\"") > -1 || name.indexOf("\“") > -1 || name.indexOf("\”") > -1) {
		alert('不能包含双引号');
		return false;
	}
	if (tid == 0 && name.length > 5) {
		alert('一级菜单名称不能超过5个汉字!');
		return false;
	}
	if (tid != 0 && name.length > 8) {
		alert('二级菜单名称不能超过8个汉字!');
		return false;
	}
	if (type == 'view' && url == '') {
		alert('链接不能为空!');
		return false;
	}
	if (url != "" && url.indexOf('http') < 0) {
		alert('链接必须以http开头!');
		return false;
	}
	if (url.indexOf("\"") > -1 || url.indexOf("\“") > -1 || url.indexOf("\”") > -1) {
		alert('不能包含双引号');
		return false;
	}
	if (content.indexOf("\"") > -1 || content.indexOf("\“") > -1 || content.indexOf("\”") > -1) {
		alert('不能包含双引号');
		return false;
	}
	alert('保存成功!');
	return true;
}

// 组装整个树菜单JSON数据
function getMenuJson() {
	//基本菜单格式，也就是一个节点的信息   node =  {"name":"短信笑话","type":"click","url":"","key":"13"}
	//只有一级没二级的菜单格式      {"name":"短信笑话","type":"click","url":"","key":"13"}
	//一级下有二级的菜单格式           {"name":"游戏娱乐","sub_button":[node1, node2,]}
	//最外层的格式      	{"button":[          ]}
	
	// 菜单json
	var menu_json = "";
	// 整个菜单
	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
	//查找一级节点
	var nodes = zTree.getNodesByParam("pid", "0", null);
	for (var j = 1; j < nodes.length; j++) {
		// 设置一级菜单
		var node_1st = nodes[j];
		
		var id = nodes[j].id;
		//alert('id='+id);
		//查找二级节点集合
		var node_2nd_arr = zTree.getNodesByParam("pid", id, null);
		var node_2nd = '';
		for (var k = 0; k < node_2nd_arr.length; k++) {
			if (node_2nd_arr[k] != null) {
				// 设置二级菜单
				var node = setMenuNode(node_2nd_arr[k]);
				node_2nd += JSON.stringify(node) + ',';
			}
		}
		// 删除最后一个逗号
		node_2nd = node_2nd.substring(0, node_2nd.length - 1);
		//一级下有二级
		if (node_2nd_arr.length > 0) {
			menu_json += '{"name":"' + node_1st.name + '","sub_button":[' + node_2nd + ']},';
		} else { //只有一级没有二级
			node_1st = setMenuNode(node_1st);
			menu_json += JSON.stringify(node_1st) + ',';
		}
	}
	// 删除最后一个逗号
	menu_json = menu_json.substring(0, menu_json.length - 1);
	var json = '{"button":[' + menu_json + ']}';
	//console.log('json', json);
	return json;
}

/**
 * 设置自定义菜单节点
 * @param node
 * @returns
 */
function setMenuNode(node) {
	var menuNode = new Object();
	menuNode.name = node.name;
	menuNode.type = node.type.indexOf('click') > -1 ? 'click' : node.type;
	if (menuNode.type == 'click' || menuNode.type == 'pic_photo_or_album' || 
			menuNode.type == 'pic_sysphoto' || menuNode.type == 'pic_weixin') {
		menuNode.key = (node.mkey != undefined && node.mkey != '') ? node.mkey : node.id;
	}
	if (menuNode.type == 'view') {
		menuNode.url = node.url;
	}
	// 小程序
	if (menuNode.type == 'miniprogram') {
		menuNode.appid = node.appid;
		menuNode.pagepath = node.pagepath;
		menuNode.url = "http://mp.weixin.qq.com";
	}
	return menuNode;
}

// 菜单预览
function previewMenu() {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
	//查找一级节点
	var nodes = zTree.getNodesByParam("pid", "0", null);
	var html = "", ndstr1 = "";
	for (var j = 1; j < nodes.length; j++) {
		if (nodes[j] != null) {
			var id = nodes[j].id;
			var name = nodes[j].name; //一级菜单名称
			ndstr1 = '<li id="preview_' + j + '" class="previewlevel1 pre_nav ">' + '<a href="javascript:;" class="pre_nav_btn" onclick="show(' + j + ');">' + name + '</a></li>';
			//查找二级节点集合
			var nds = zTree.getNodesByParam("pid", id, null);
			var ndstr2 = "", str2 = "";
			if (j == 2) {
				str2 = '<ul class="pre_sub_nav_list" id="show' + j + '" style="display:none;margin-left:90px;"><span class="pre_sub_nav_arrow"></span>';
			} else if (j == 3) {
				str2 = '<ul class="pre_sub_nav_list" id="show' + j + '" style="display:none;margin-left:150px;"><span class="pre_sub_nav_arrow"></span>';
			} else {
				str2 = '<ul class="pre_sub_nav_list" id="show' + j + '" style="display:none;"><span class="pre_sub_nav_arrow"></span>';
			}

			for (var k = 0; k < nds.length; k++) {
				if (nds[k] != null) {
					ndstr2 += '<li class="previewlevel2 pre_sub_nav" style="letter-spacing:0px;"><a href="javascript:;" class="pre_sub_nav_btn">' + nds[k].name + '</a></li>';
				}
			}
		}
		html += ndstr1 + str2 + ndstr2 + '</ul>';
	}
	html = '<ul id="preview_screen1" class="pre_nav_list">' + html + '</ul>';
	//alert(html);
	$('#pre_nav_wrapper').html(html);
	$('#preview_box').show();
}

// 显示二级菜单
function show(id) {
	for (var i = 1; i < 4; i++) {
		if (i == id) {
			$('#show' + id).show();
		} else {
			$('#show' + i).hide();
		}
	}
}

// 显示图文html
function showImgTxtHtml(id) {
	$.post(path + "/menu/findImgTxtHtml", { pubno: $('#pubno').val(), menuId: id },
	function(data) {
		if (data != null && data != "") {
			$('#preViewDiv').html(data);
		}
	});
}

// 关闭预览
function closePreView() {
	$('#preview_box').hide();
}